package product.application.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import product.domain.model.Product;
import product.domain.repository.ProductRepository;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Product createProduct(Product product) {
        product.setIsDeleted(false);
        return productRepository.save(product);
    }

    // ✅ 替换为按 ID 更新的 update 方法
    public Product updateProduct(Integer id, Product updatedProduct) {
        Optional<Product> optional = productRepository.findById(id);
        if (optional.isEmpty()) {
            throw new RuntimeException("Product not found with ID: " + id);
        }
        Product existing = optional.get();

        // 更新字段
        existing.setProductName(updatedProduct.getProductName());
        existing.setProductionDate(updatedProduct.getProductionDate());
        existing.setProductionPeriod(updatedProduct.getProductionPeriod());
        existing.setProductionPlace(updatedProduct.getProductionPlace());
        existing.setCategory(updatedProduct.getCategory());
        existing.setProductPrice(updatedProduct.getProductPrice());
        existing.setStock(updatedProduct.getStock());
        existing.setProductImageUrl(updatedProduct.getProductImageUrl());
        if (updatedProduct.getClickCount() != null) {
            existing.setClickCount(updatedProduct.getClickCount());
        }

        if (updatedProduct.getStatus() != null) {
            existing.setStatus(updatedProduct.getStatus());
        }
        existing.setIsDeleted(updatedProduct.getIsDeleted());

        return productRepository.save(existing);
    }

    public void deleteProduct(Integer productId) {
        productRepository.deleteById(productId);
    }

    public Optional<Product> getProductById(Integer productId) {
        return productRepository.findById(productId);
    }

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    // ✅ 按用户ID查询产品
    public List<Product> getByUserId(Long userId) {
        return productRepository.findByUserId(userId);
    }

    // ✅ 按分类查询产品
    public List<Product> getByCategory(String category) {
        return productRepository.findByCategory(category);
    }
}